package com.qf.hw.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.qf.hw.domain.Student;
import com.qf.hw.service.StudentService;
import com.qf.hw.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet("/stu")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决响应乱码
        resp.setContentType("application/json;charset=utf-8");
        //解决post请求体的乱码问题
        req.setCharacterEncoding("gbk");

        String action = req.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询全部学生
     * @param req
     * @param resp
     */
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("findAll...");
        List<Student> students = studentService.findAll();

        /*
            结果数据不可以放到域对象，因为前端页面是html页面，不识别域对象中数据的
            一般我们在公司是将得到的数据转成json格式的字符串，写回到前端页面
            Student -- 对象-- {"name":"zhangsan","age":18}
            List<Student> -- 数组--[{},{}]

            FastJson: 核心两个功能 - ① 将Java中的对象/集合转成json格式字符串【序列化】 ② 将json格式字符串转成Java中的对象/集合【反序列化】
            Jackson
            Gson
         */
        String json = JSON.toJSONString(students);
        System.out.println(json);

        //不要做页面跳转，利用respson对象将json数据写回到前端页面
        resp.getWriter().write(json);
    }

    /**
     * 添加学生 -- post
     * @param req
     * @param resp
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("add...");

        /*
            以前前端发送到后端的数据都是 key=value&key2=value2.... 针对这种格式的数据，后端接收方式 req.getParameter("key");
            现在前后端分离后，前端发送过来的数据格式是：{"key":"value","key2":"value2",....}
                针对这种格式的数据，只能通过获取请求体的流的方式接收
         */

        ServletInputStream is = req.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));

        System.out.println("你好。。。");

        String line = br.readLine();

        //利用json工具，将字符串反序列化成JAVA对象
        //将[{}]--List<>
//        JSON.parseArray()
        //将{}--Obj
        if (line!=null && line.length()!=0) {
            Student stu = JSON.parseObject(line, Student.class);

            int count = studentService.insert(stu);

            resp.getWriter().write(count+"");
        }
    }

    private void findPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageNumStr = req.getParameter("pageNum"); //null  ""
        String pageSizeStr = req.getParameter("pageSize");

        int pageNum = 1;
        int pageSize = 5;

        try {
            pageNum = Integer.parseInt(pageNumStr);
        }catch (Exception e){}
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        }catch (Exception e){}

        PageInfo<Student> pageInfo = studentService.findPage(pageNum, pageSize);

        String json = JSON.toJSONString(pageInfo);

        resp.getWriter().write(json);
    }


}
